#include "ThreadPool.h"

void ThreadPool::threadFunc(void *args)
{
    ThreadPool *pool = static_cast<ThreadPool *>(args);
    while (1)
    {
        std::unique_ptr<Task> task = std::move(pool->processTask());

        task->run(nullptr);
    }
}

void ThreadPool::init()
{
    for (size_t idx{}; idx < _poolSize; idx++)
    {
        _threads.emplace_back(thread(&ThreadPool::threadFunc, this));
    }
}

ThreadPool::ThreadPool(size_t poolSize, size_t taskSize)
    : _poolSize{poolSize}, _taskSize{taskSize}, _tasks{taskSize}
{
    _threads.reserve(_poolSize);
    init();
}

ThreadPool::~ThreadPool()
{
    for (thread &th : _threads)
    {
        if (th.joinable())
        {
            th.join();
        }
    }
}

std::unique_ptr<Task> ThreadPool::processTask()
{
    return _tasks.front();
}

void ThreadPool::addTask(Task *task)
{
    _tasks.push_back(task);
}
